package com.dhecp.project.system.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.layui.TreeDataModel;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.system.domain.MailAddressBook;
import com.dhecp.project.system.domain.MailContent;
import com.dhecp.project.system.mapper.MailContentMapper;
import com.dhecp.project.system.service.MailContentService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 邮件系统 服务层
 * @author DH-Xxj
 * @version 2020年9月18日
 */
@Service
public class MailContentServiceImpl implements MailContentService {
	
    @Autowired
    private MailContentMapper mailContentMapper;

	@Autowired
	private SysDictionaryForFieldService dictionaryForFieldService;


	/**
	 * 查询当前用户草稿邮件数
	 * @param params 无需参数
	 * @return int - mailCgCount
	 * @author DH-Xxj
	 */
	@Override
	public Integer queryModuleMailCgs(Map<String, Object> params) {
		params.put("fromUser", ShiroUtils.getUserId());
		return mailContentMapper.selectCgs(params);
	}

	/**
	 * 查询当前用户未读邮件数
	 * @param params 无需参数
	 * @return int - mailWdCount
	 * @author DH-Xxj
	 */
	@Override
	public Integer queryModuleMailWds(Map<String, Object> params) {
		params.put("recUser", ShiroUtils.getUserId());
		return mailContentMapper.selectWds(params);
	}
	
	/**
	 * 通过邮件Guid查询发件箱信息、邮件发件人、邮件主要内容（不含收件人列表信息）
	 * @param guid 邮件Guid
	 * @return
	 * @author DH-Xxj
	 */
	@Override
	public MailContent selectMainContentByGuid(Map<String, Object> params){
		return mailContentMapper.findMainContentByGuid(params);
	}
	
	/**
	 * 通过收件人Guid查询邮件详细内容（含收件人列表信息）
	 * @param guid 收件人Guid
	 * @return
	 * @author DH-Xxj
	 */
	@Override
	public MailContent selectMailContentByGuid(Map<String, Object> params){
		return mailContentMapper.findMailContentByGuid(params);
	}
	
    /**
     * 查询发件箱信息、邮件发件人、邮件主要内容（不含收件人列表信息）
     * @param params
     * @return
     * @author DH-Xxj
     * @throws Exception 
     */
    @Override
    public List<MailContent> selectMainContentList(Map<String, Object> params) throws Exception {
    	params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));
		if (params.get("field") == null || params.get("field") == ""){
			String orderBy = "t1.SendTime desc";
			PageUtils.startPageOrder(orderBy);
		}else{
			PageUtils.startPage();	
		}
        return mailContentMapper.findMainContentList(params);
    }

    /**
     * 查询收件箱信息
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<MailContent> selectMailContentList(Map<String, Object> params) throws Exception {
    	params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));
		if (params.get("field") == null || params.get("field") == ""){
			String orderBy = "t2.readed asc, t1.SendTime desc";
			PageUtils.startPageOrder(orderBy);
		}else{
			PageUtils.startPage();	
		}
        return mailContentMapper.findMailContentList(params);
    }

    /**
     * 查询已删除邮件
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<MailContent> selectDeletedMailList(Map<String, Object> params) throws Exception {
    	params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));
		if (params.get("field") == null || params.get("field") == ""){
			String orderBy = "t1.SendTime desc";
			PageUtils.startPageOrder(orderBy);
		}else{
			PageUtils.startPage();	
		}
        return mailContentMapper.findDeletedMailList(params);
    }

    /**
     * 查询保留邮件
     * @param params
     * @return
     * @throws Exception
     * @author DH-Xxj
     */
    @Override
    public List<MailContent> selectPerpetualMailList(Map<String, Object> params) throws Exception {
    	params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));
		if (params.get("field") == null || params.get("field") == ""){
			String orderBy = "t1.SendTime desc";
			PageUtils.startPageOrder(orderBy);
		}else{
			PageUtils.startPage();	
		}
        return mailContentMapper.findPerpetualMailList(params);
    }

	/**
	 * 获取邮件系统地址簿树
	 * @param params
	 * @return List-TreeDataModel
	 * @author DH-Xxj
	 */
	@Override
	public List<TreeDataModel> queryMailAddressBookTree(Map<String, Object> params){
		params.put("userId", ShiroUtils.getUserId());
		return mailContentMapper.findMailAddressBookTree(params);
	}

    /**
     * 保存草稿、发送邮件
     * @param mailType 邮件状态[已发送、草稿、撤销]
     * @param infoItems 必要参数：邮件主表对应实体类的json格式字符串
     * 	guid、pGuid、主题、正文、收件人类型编码、收件人、抄送类型编码、抄送、密送类型编码、密送、附件关联、邮件标签、重要邮件、删除标记、彻底删除标记
     * @return AjaxResult
     * @author DH-Xxj
     */
    @Override
    public AjaxResult insertMainContent(Map<String, Object> params) {
        List<MailContent> mailContentList = JSON.parseArray(params.get("infoItems").toString(), MailContent.class);
        if (mailContentList == null || mailContentList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        String recUsers = "";	//本次发送邮件对应收件人编号字符串，如：1001,1002,1003
        String mailType = "草稿";
        if (params.get("mailType") != null && params.get("mailType") != ""){
        	mailType = params.get("mailType").toString();
        }
        for (MailContent mailContent : mailContentList) {
            String guid = RandomValueUtils.getGUID();
            mailContent.setMailType(mailType);
            mailContent.setCreateTime(new Date());
            mailContent.setSendTime(new Date());
            mailContent.setFromCid(ShiroUtils.getUserCid());
            mailContent.setFromCidName(ShiroUtils.getUserCidName());
            mailContent.setFromDept(ShiroUtils.getUserDeptPath());
            mailContent.setFromDeptName(ShiroUtils.getUserDeptName());
            mailContent.setFromUser(ShiroUtils.getUserId());
            mailContent.setFromUserName(ShiroUtils.getUserName());
            
        	if (mailContent.getGuid() != null && !"".equals(mailContent.getGuid())){
        		guid = mailContent.getGuid();
            }
        	MailContent thisMailContent = mailContentMapper.checkMainContentByGuid(guid);
        	if (thisMailContent == null){	//新增
                mailContent.setGuid(guid);
        		mailContentMapper.insertMainContent(mailContent);
        	}else{	//修改
        		mailContentMapper.updateMainContent(mailContent);
        	}

        	//查询本邮件所有收件人信息，并将收件人编号组装成字符串recUsers
        	if ("已发送".equals(mailContent.getMailType())){
            	List<MailContent> recipientList = mailContentMapper.findRecipientByGuid(guid);
            	if (recipientList != null && recipientList.size() > 0){
            		for (MailContent recipient : recipientList){
            			if ("".equals(recUsers)) recUsers = recipient.getRecUser();
            			else recUsers = recUsers + "," + recipient.getRecUser();
            		}
            	}
        	}
        }
        return AjaxResult.success("操作成功", recUsers);
    }

    /**
     * 修改邮件状态（已发送、草稿、撤销），只改状态 不改其它内容
     * @param infoItems 必要参数：邮件主表对应实体类的json格式字符串（包含：guid，mailType 邮件状态（已发送、草稿、撤销））
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateMailType(Map<String, Object> params) {
        List<MailContent> mailContentList = JSON.parseArray(params.get("infoItems").toString(), MailContent.class);
        if (mailContentList == null || mailContentList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        String recUsers = "";	//本次发送邮件对应收件人编号字符串，如：1001,1002,1003
        for (MailContent mailContent : mailContentList) {
        	String guid = mailContent.getGuid();
        	params.put("guid", guid);
        	params.put("mailType", mailContent.getMailType());
        	mailContentMapper.updateMainContentForMailType(params);

        	//查询本邮件所有收件人信息，并将收件人编号组装成字符串recUsers
        	if ("已发送".equals(mailContent.getMailType())){
            	List<MailContent> recipientList = mailContentMapper.findRecipientByGuid(guid);
            	if (recipientList != null && recipientList.size() > 0){
            		for (MailContent recipient : recipientList){
            			if ("".equals(recUsers)) recUsers = recipient.getRecUser();
            			else recUsers = recUsers + "," + recipient.getRecUser();
            		}
            	}
        	}
        }
        return AjaxResult.success("操作成功", recUsers);
    }

    /**
     * 修改收件箱邮件已读标记
     * @param infoItems 必要参数：邮件主表对应实体类的json格式字符串（包含：guid，readed 已读标记）
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateReaded(Map<String, Object> params) {
        List<MailContent> mailContentList = JSON.parseArray(params.get("infoItems").toString(), MailContent.class);
        if (mailContentList == null || mailContentList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (MailContent mailContent : mailContentList) {
        	params.put("guid", mailContent.getGuid());
        	params.put("readed", mailContent.getReaded());
        	params.put("readTime", new Date());
        	mailContentMapper.updateRecipientForReaded(params);
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改邮件删除标记
     * @param infoItems 必要参数：邮件主表对应实体类的json格式字符串（包含：guid，deleted 删除标记，mailType 邮件状态（已收件、已发送、草稿、撤销））
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateDeleted(Map<String, Object> params) {
        List<MailContent> mailContentList = JSON.parseArray(params.get("infoItems").toString(), MailContent.class);
        if (mailContentList == null || mailContentList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (MailContent mailContent : mailContentList) {
        	params.put("guid", mailContent.getGuid());
        	params.put("deleted", mailContent.getDeleted());
        	params.put("deletedTime", new Date());
        	if ("已收件".equals(mailContent.getMailType())){
        		mailContentMapper.updateRecipientForDeleted(params);
        	}else{
            	mailContentMapper.updateMainContentForDeleted(params);
        	}
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改邮件彻底删除标记
     * @param infoItems 必要参数：邮件主表对应实体类的json格式字符串（包含：guid，deletedSup 彻底删除标记，mailType 邮件状态（已收件、已发送、草稿、撤销））
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateDeletedSup(Map<String, Object> params) {
        List<MailContent> mailContentList = JSON.parseArray(params.get("infoItems").toString(), MailContent.class);
        if (mailContentList == null || mailContentList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (MailContent mailContent : mailContentList) {
        	params.put("guid", mailContent.getGuid());
        	params.put("deletedSup", mailContent.getDeletedSup());
        	params.put("deletedSupTime", new Date());
        	if ("已收件".equals(mailContent.getMailType())){
        		mailContentMapper.updateRecipientForDeletedSup(params);
        	}else{
            	mailContentMapper.updateMainContentForDeletedSup(params);
        	}
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改邮件标签
     * @param infoItems 必要参数：邮件主表对应实体类的json格式字符串（包含：guid，mailLabel 邮件标签，mailType 邮件状态（已收件、已发送、草稿、撤销））
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateMailLabel(Map<String, Object> params) {
        List<MailContent> mailContentList = JSON.parseArray(params.get("infoItems").toString(), MailContent.class);
        if (mailContentList == null || mailContentList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (MailContent mailContent : mailContentList) {
        	params.put("guid", mailContent.getGuid());
        	params.put("mailLabel", mailContent.getMailLabel());
        	if ("已收件".equals(mailContent.getMailType())){
        		mailContentMapper.updateRecipientForMailLabel(params);
        	}else{
            	mailContentMapper.updateMainContentForMailLabel(params);
        	}
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改重要邮件标记
     * @param infoItems 必要参数：邮件主表对应实体类的json格式字符串（包含：guid，important 重要邮件，mailType 邮件状态（已收件、已发送、草稿、撤销））
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateImportant(Map<String, Object> params) {
        List<MailContent> mailContentList = JSON.parseArray(params.get("infoItems").toString(), MailContent.class);
        if (mailContentList == null || mailContentList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (MailContent mailContent : mailContentList) {
        	params.put("guid", mailContent.getGuid());
        	params.put("important", mailContent.getImportant());
        	if ("已收件".equals(mailContent.getMailType())){
        		mailContentMapper.updateRecipientForImportant(params);
        	}else{
            	mailContentMapper.updateMainContentForImportant(params);
        	}
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改保留邮件标记
     * @param infoItems 必要参数：邮件主表对应实体类的json格式字符串（包含：guid，perpetual 保留邮件，mailType 邮件状态（已收件、已发送、草稿、撤销））
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updatePerpetual(Map<String, Object> params) {
        List<MailContent> mailContentList = JSON.parseArray(params.get("infoItems").toString(), MailContent.class);
        if (mailContentList == null || mailContentList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (MailContent mailContent : mailContentList) {
        	params.put("guid", mailContent.getGuid());
        	params.put("perpetual", mailContent.getPerpetual());
        	if ("已收件".equals(mailContent.getMailType())){
        		mailContentMapper.updateRecipientForPerpetual(params);
        	}else{
            	mailContentMapper.updateMainContentForPerpetual(params);
        	}
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 新增邮件系统地址簿信息
     * @param infoItems 必要参数：邮件系统地址簿对应实体类的json格式字符串（包含：pGuid【上级Guid，顶级分组默认"root"】,title【组名、公司名称、部门名称、用户名称】,vtype【取值：menu,company,dept,user】,orgid【公司编码、部门编码、用户编码】）
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult insertMailAddressBook(Map<String, Object> params) {
        List<MailAddressBook> mailAddressBookList = JSON.parseArray(params.get("infoItems").toString(), MailAddressBook.class);
        if (mailAddressBookList == null || mailAddressBookList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (MailAddressBook mailAddressBook : mailAddressBookList) {
        	mailAddressBook.setGuid(RandomValueUtils.getGUID());
        	mailAddressBook.setUserId(ShiroUtils.getUserId());
        	if ("menu".equals(mailAddressBook.getVtype().toString().toLowerCase())){
        		mailAddressBook.setBookOrder(2000);
        		mailAddressBook.setAllowAdd(true);
        		mailAddressBook.setAllowEdit(true);
        	}else{
        		mailAddressBook.setBookOrder(2001);
        		mailAddressBook.setAllowAdd(false);
        		mailAddressBook.setAllowEdit(false);
        	}
        	mailAddressBook.setAllowDelete(true);
        	mailContentMapper.insertMailAddressBook(mailAddressBook);
        }
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改邮件系统地址簿分组名称
     * @param guid
     * @param title 名称
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult updateMailAddressBookForTitle(Map<String, Object> params) {
    	if (params.get("guid") == null || params.get("guid") == ""){
    		return AjaxResult.error("请提供行唯一值【guid】。");
    	}
    	if (params.get("title") == null || params.get("title") == ""){
    		return AjaxResult.error("请提供修改后的名称【title】。");
    	}
    	mailContentMapper.updateMailAddressBookForTitle(params);
        return AjaxResult.success("操作成功");
    }

    /**
     * 通过Guid删除邮件系统地址簿信息
     * @param guid
     * @return
     * @author DH-Xxj
     */
    @Override
    public AjaxResult deleteMailAddressBook(Map<String, Object> params) {
    	String guid = "";
    	if (params.get("guid") == null || params.get("guid") == ""){
    		return AjaxResult.error("请提供行唯一值【guid】。");
    	}else{
    		guid = params.get("guid").toString();
    	}
    	mailContentMapper.deleteMailAddressBookByGuid(guid);
    	mailContentMapper.deleteMailAddressBookForInvalid(guid);
        return AjaxResult.success("操作成功");
    }
    
}
